<template>
  <div>
    <UploadDragger
      v-model:fileList="fileList"
      name="file"
      :multiple="true"
      :customRequest="handlePreview"
      @download="downLoadFile"
      @change="handleChange"
      @remove="handleRemove"
    >
      <p class="ant-upload-drag-icon">
        <inbox-outlined />
      </p>
      <p class="ant-upload-text">{{ props.contentText }}</p>
      <p class="ant-upload-hint"> 支持所有文件格式，单个文件不超过10M </p>
      <template #itemRender="{ file, actions }">
        <div>
          <div class="flex mt-[10px]">
            <span
              class="mr-[20px] whitespace-nowrap"
              :style="file.status === 'error' ? 'color: red' : ''"
              >{{ file.name }}</span
            >
            <Progress
              :percent="file.status === 'done' ? 100 : 0"
              :showInfo="file.status === 'done'"
            />
          </div>
          <a class="mr-[20px]" href="javascript:;" @click="setVisible(file)">预览</a>
          <a class="mr-[20px]" href="javascript:;" @click="actions.download">下载</a>
          <a
            class="mr-[20px]"
            href="javascript:;"
            @click="
              () => {
                // selectFile = file;
                handleCreatePrompt(file);
              }
            "
            >重命名</a
          >
          <a class="mr-[20px]" href="javascript:;" @click="actions.remove">删除</a>
        </div>
      </template>
    </UploadDragger>

    <Image
      :width="200"
      :style="{ display: 'none' }"
      :preview="{
        visible: imgVisibleObj.visible,
        onVisibleChange: setVisible,
      }"
      :src="imgVisibleObj.src"
    />

    <!-- <Modal
      v-model:open="selectFile"
      title="重命名"
      ok-text="确认"
      cancel-text="取消"
      @ok="handleRenameFile"
      @cancel="selectFile = false"
    >
      <Input v-model:value="selectFile.name" />
    </Modal> -->
  </div>
</template>
<script lang="ts" setup>
  import { ref, defineProps, defineOptions, defineEmits, onMounted, nextTick, watch } from 'vue';
  import { InboxOutlined } from '@ant-design/icons-vue';
  import { message, UploadDragger, Progress, Image } from 'ant-design-vue';
  import type { UploadChangeParam } from 'ant-design-vue';
  import { UploadRequestOption } from 'ant-design-vue/lib/vc-upload/interface';

  import { createPrompt } from '@/components/Prompt';

  import { uploadApi, renameFileApi, delFileApi, downloadFileApi } from '@/api/escloud/upload';
  import { downloadFile } from '@/utils/common/index';
  // import { v4 as uuidv4 } from 'uuid';

  defineOptions({ name: 'BasicUploadDragger' });

  const props = defineProps({
    params: { type: [Object] },
    fileLists: { type: Array, default: () => [] },
    contentText: { type: String, default: '点击或将文件拖拽至此上传' },
    propUploadApi: { type: Function },
  });
  const emit = defineEmits(['uploadResult', 'changeFileRes']);
  const fileList = ref<any>([]);
  // 重命名文件
  // const selectFile = ref<any>(false);
  // 预览图
  const imgVisibleObj = ref<any>({
    visible: false,
    src: '',
  });

  function handleCreatePrompt(file) {
    createPrompt({
      title: '文件重命名',
      required: true,
      label: '文件名',
      defaultValue: file.name,
      onOK: (name: string) => {
        handleRenameFile({
          ...file,
          name,
        });
      },
      inputType: 'Input',
    });
  }

  onMounted(() => {
    fileList.value = props.fileLists.map((item: any) => {
      return {
        ...item,
        name: item.fileOriginName || item.name,
        status: 'done',
      };
    });
  });

  watch(
    () => props.fileLists,
    (newVal, oldVal) => {
      if (newVal !== oldVal) {
        fileList.value = props.fileLists.map((item: any) => {
          return {
            ...item,
            name: item.fileOriginName || item.name,
            status: 'done',
          };
        });
      }
    },
    { deep: true }, // 如果 fileLists 是一个深层嵌套的对象数组，可能需要开启深度监听
  );

  // 预览模块
  const setVisible = (file): void => {
    var patterns = /.(jpg|jpeg|png|gif|bmp|JPG|PNG|GIF|BMP|JPEG)$/;
    if (patterns.test(file.fileOriginName) || !file) {
      imgVisibleObj.value = {
        visible: !!file,
        src: file ? file.fileUrl : '',
      };
    } else {
      window.open(file.fileUrl, '_blank');
    }
  };

  // 下载文件
  const downLoadFile = async (file) => {
    try {
      const data = (await downloadFileApi(file.fileUrl)) as any;
      if (data) {
        downloadFile(data, file.name);
      } else {
        message.error('下载失败');
        return false;
      }
    } catch (error) {
      return false;
    }
  };

  const handleChange = (info: UploadChangeParam) => {
    const status = info.file.status;

    if (status === 'done') {
      fileList.value = fileList.value.map((item) => {
        return {
          ...item,
          ...item.response,
        };
      });
    } else if (status === 'error') {
      fileList.value = fileList.value
        .map((item) => {
          if (item.uid === info.file.uid) {
            return null;
          } else {
            return item;
          }
        })
        .filter((ele) => {
          return ele;
        });
      message.error(`${info.file.name} 上传失败`);
    }
  };

  const handlePreview = async (info: UploadRequestOption<any>) => {
    const { onSuccess, onError, file } = info;
    const form = new FormData();
    // const batchId = uuidv4().split('-').join('');
    for (let key in props.params) {
      form.append(key, props.params[key]);
    }
    form.append('file', file);
    // form.append('batchId', batchId);
    const upload = props.propUploadApi ? props.propUploadApi : uploadApi;

    try {
      const res = await upload(form);
      console.log('上传结果', res);
      if (res) {
        emit('uploadResult', res);
        nextTick(() => {
          emit('changeFileRes', fileList.value);
        });
        message.success('上传成功');

        onSuccess &&
          onSuccess({
            ...res,
          });
      } else {
        message.error('上传失败');
        onError && onError(res);
      }
    } catch (error) {
      onError && onError(error);
    }
  };

  const handleRemove = async (file: any): Promise<void | boolean> => {
    try {
      const res = await delFileApi(file.id);
      res && message.success('删除成功');
      nextTick(() => {
        emit('changeFileRes', fileList.value);
      });
      return !!res;
    } catch (error) {
      // message.error(error);
      return false;
    }
  };

  const handleRenameFile = async (file) => {
    if (!file.id) {
      message.error('未找到id');
      return;
    } else if (!file.name) {
      message.error('请填写文件名');
      return;
    }
    const params = {
      id: file.id,
      name: file.name,
    };
    try {
      const res = (await renameFileApi(params)) as any;
      if (res) {
        fileList.value.forEach((element) => {
          if (element.id === file.id) {
            element.name = params.name;
          }
        });
        // selectFile.value = false;
        message.success('重命名成功！');
      } else {
        message.error('重命名失败！');
      }
    } catch (error) {
      // message.error(error);
    }
  };
</script>
